//
//  DestinationController.m
//  MyTrip
//
//  Created by zhang on 15/8/22.
//  Copyright (c) 2015年 张益. All rights reserved.
//

#import "DestinationController.h"
#import "HMSegmentedControl.h"
#import "AsyncGETConnection.h"
#import "IndexDes.h"
#import "Destination.h"
#import "DestinationCell.h"
#import "TypeController.h"
#import "DesDetailController.h"
#import "MBProgressHUD.h"
#import "SearchController.h"




@interface DestinationController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewAccessibilityDelegate,UIScrollViewDelegate, TypeControllerDelegate, DestinationCellDelegate>

@property (nonatomic, retain) HMSegmentedControl *segmentedControl;
@property (nonatomic, retain) UICollectionView *titleCollection;
@property (nonatomic, retain) NSMutableArray *destinArray;
@property (nonatomic, retain) NSMutableArray *indexArray;
@property (nonatomic, retain) NSMutableArray *indexOneArray;
@property (nonatomic, retain) NSMutableArray *indexTwoArray;
@property (nonatomic, retain) NSMutableArray *indexThreeArray;
@property (nonatomic, retain) NSMutableArray *indexFourArray;
@property (nonatomic, retain) NSMutableArray *indexFiveArray;
@property (nonatomic, retain) NSMutableArray *indexSixArray;
@property (nonatomic, retain) NSMutableArray *indexSevenArray;
@property (nonatomic, retain) NSMutableArray *indexEightArray;
@property (nonatomic, retain) MBProgressHUD *hud;



@end

@implementation DestinationController

- (void)dealloc
{
    [_indexEightArray release];
    [_indexSevenArray release];
    [_indexSixArray release];
    [_indexFiveArray release];
    [_indexFourArray release];
    [_indexTwoArray release];
    [_indexThreeArray release];
    [_indexOneArray release];
    [_indexArray release];
    [_destinArray release];
    [_segmentedControl release];
    [_titleCollection release];
    [super dealloc];
}

- (instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.destinArray = [NSMutableArray array];
        self.indexArray = [NSMutableArray array];
        self.indexOneArray = [NSMutableArray array];
        self.indexTwoArray = [NSMutableArray array];
        self.indexThreeArray = [NSMutableArray array];
        self.indexFourArray = [NSMutableArray array];
        self.indexFiveArray = [NSMutableArray array];
        self.indexSixArray = [NSMutableArray array];
        self.indexSevenArray = [NSMutableArray array];
    }
    return self;
}


#pragma mark - typeAction
- (void)typeAction:(UIButton *)button{
    TypeController *type = [[TypeController alloc] init];
    type.delegate = self;
    type.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    [self presentViewController:type animated:YES completion:^{
        
    }];
    [type release];
}

- (void)searchAction:(UIButton *)button{
    SearchController *search = [[SearchController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
    [search release];
}

- (void)moreAction:(UIButton *)button{
    if (_segmentedControl.selectedSegmentIndex < 6) {
        NSLog(@"%ld", _segmentedControl.selectedSegmentIndex);
        _segmentedControl.selectedSegmentIndex  = _segmentedControl.selectedSegmentIndex + 1;
        self.titleCollection.contentOffset = CGPointMake(_segmentedControl.selectedSegmentIndex * self.view.frame.size.width, 0);
    }
    
}



#pragma mark - TypeControllerDelegate
- (void)receiveTag:(NSInteger)tag{
    
    _segmentedControl.selectedSegmentIndex = tag - 1;
    self.titleCollection.contentOffset = CGPointMake(_segmentedControl.selectedSegmentIndex * self.view.frame.size.width, 0);
}

#pragma mark - segmentedControl创建
- (void)createSegmentedControl{
    UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    aView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: aView];
    [aView release];
    
    UIButton *typeButton = [[[UIButton alloc] initWithFrame:CGRectMake((375 - 55 + 15)  * OffWidth, 5 * OffHeight, 30 * OffWidth, 30 * OffHeight)] autorelease];
    [typeButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"typeNormal" ofType:@"png"]] forState:UIControlStateNormal];
    [typeButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"typeTouch" ofType:@"png"]] forState:UIControlStateHighlighted];
    [typeButton addTarget:self action:@selector(typeAction:) forControlEvents:UIControlEventTouchUpInside];
    [aView addSubview:typeButton];
    
    UIButton *searchButton = [[[UIButton alloc] initWithFrame:CGRectMake((375 - 55 + 15 - 35) * OffWidth, 3 * OffHeight, 30 * OffWidth, 30 * OffHeight)] autorelease];
    [searchButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"search" ofType:@"png"]] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [aView addSubview:searchButton];
    
    UIButton *moreButton = [[[UIButton alloc] initWithFrame:CGRectMake((375 - 30 - 35 - 40) * OffWidth, 2 * OffHeight, 35 * OffWidth, 35 * OffHeight)] autorelease];
    [moreButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"more" ofType:@"png"]] forState:UIControlStateNormal];
    [moreButton addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    [aView addSubview:moreButton];
    
    
    self.segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"本月推荐", @"热门地点", @"国内城市", @"港澳台", @"欧洲国家", @"美洲国家", @"亚洲国家"]];
    self.segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    self.segmentedControl.frame = CGRectMake(10 * OffWidth, 0, (375 - 55 - 55) * OffWidth, 40 * OffHeight);
    self.segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10);
    self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
    self.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    [self.segmentedControl setTitleFormatter:^NSAttributedString *(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {
        NSAttributedString *attString = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName : [UIColor grayColor]}];
        return attString;
    }];
    [self.segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    [aView addSubview:_segmentedControl];
    
}

- (void)uisegmentedControlChangedValue:(UISegmentedControl *)segmentedControl {
    
    NSLog(@"Selected index = %ld", (long)segmentedControl.selectedSegmentIndex);
}

#pragma mark --- segmentControl 控制下面collectionView 的偏移量
- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
    
    NSLog(@"Selected index = %ld ", (long)segmentedControl.selectedSegmentIndex);
    
    self.titleCollection.contentOffset = CGPointMake(segmentedControl.selectedSegmentIndex * self.view.frame.size.width, 0);
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    CGFloat pageWidth = self.view.frame.size.width;
    NSInteger page = self.titleCollection.contentOffset.x / pageWidth;
    
    [self.segmentedControl setSelectedSegmentIndex:page animated:YES];
}

#pragma mark--- 创建collectionView
-(void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 250);
    
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0.1, 0, 0.1);
    self.titleCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height - 250) collectionViewLayout:flowLayout];
    self.titleCollection.pagingEnabled = YES;
    self.titleCollection.dataSource = self;
    self.titleCollection.delegate = self;
    self.titleCollection.backgroundColor = [UIColor whiteColor];
    
#pragma mark-- 偏移量
    self.titleCollection.contentSize = CGSizeMake(self.view.frame.size.width * (10 * OffWidth), 0);
    self.titleCollection.contentOffset = CGPointMake(0, 0);
    
    self.titleCollection.pagingEnabled = YES;
    
    [self.titleCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [_titleCollection registerClass:[DestinationCell class] forCellWithReuseIdentifier:@"destination"];
    [self.view addSubview:_titleCollection];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 7;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DestinationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"destination" forIndexPath:indexPath];
    cell.delegate = self;
    if (indexPath.row == 0) {
        cell.indexArray = _indexOneArray;
    }
    if (indexPath.row == 1) {
        cell.indexArray = _indexTwoArray;

    }
    if (indexPath.row == 2) {
        cell.indexArray = _indexThreeArray;
    }
    if (indexPath.row == 3) {
        cell.indexArray = _indexFourArray;
        
    }
    if (indexPath.row == 4) {
        cell.indexArray = _indexFiveArray;

    }
    if (indexPath.row == 5) {
        cell.indexArray = _indexSixArray;
    }
    if (indexPath.row == 6) {
        cell.indexArray = _indexSevenArray;

    }
    [cell.indexCollection reloadData];
    

    
    return cell;
}

- (void)getMessage{
    
    self.hud = [[MBProgressHUD alloc] init];
    [self.view addSubview:_hud];
    [_hud show:YES];
    _hud.labelText = @"正在拼命加载......";
//    在网络请求之后
   
    __block MBProgressHUD *hud = _hud;
    [AsyncGETConnection asyncGETConnectionWithURLStr:@"http://api.breadtrip.com/destination/v3/?last_modified_since=0" parameters:nil messageBlock:^(NSData *data) {
         hud.hidden = YES;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *eleArray = [dic objectForKey:@"elements"];
        for (NSDictionary *indexDic in eleArray) {
            NSArray *dataArr = [indexDic objectForKey:@"data"];
            IndexDes *indexdes = [IndexDes indexDesWithIndex:[[indexDic objectForKey:@"index"] integerValue] des:dataArr];
        
            
            
            NSInteger aIndex = [[indexDic objectForKey:@"index"] integerValue];
            if (aIndex == 0) {
                for (NSDictionary *dataDic in dataArr) {
                    Destination *destination = [Destination destiationWithVistCount:[[dataDic objectForKey:@"visited_count"] integerValue] name:[dataDic objectForKey:@"name"] cover:[dataDic objectForKey:@"cover"] wishCount:[[dataDic objectForKey:@"wish_to_go_count"] integerValue] idNum:[dataDic objectForKey:@"id"] type:[[dataDic objectForKey:@"type"] integerValue] zoomImage:[dataDic objectForKey:@"cover_route_map_cover"]];
                    [_indexOneArray addObject:destination];
                }
            }
            if (aIndex == 2) {
                for (NSDictionary *dataDic in dataArr) {
                    Destination *destination = [Destination destiationWithVistCount:[[dataDic objectForKey:@"visited_count"] integerValue] name:[dataDic objectForKey:@"name"] cover:[dataDic objectForKey:@"cover"] wishCount:[[dataDic objectForKey:@"wish_to_go_count"] integerValue] idNum:[dataDic objectForKey:@"id"] type:[[dataDic objectForKey:@"type"] integerValue] zoomImage:[dataDic objectForKey:@"cover_route_map_cover"]];
                    [_indexTwoArray addObject:destination];
                }
            }
            if (aIndex == 8) {
                for (NSDictionary *dataDic in dataArr) {
                    Destination *destination = [Destination destiationWithVistCount:[[dataDic objectForKey:@"visited_count"] integerValue] name:[dataDic objectForKey:@"name"] cover:[dataDic objectForKey:@"cover"] wishCount:[[dataDic objectForKey:@"wish_to_go_count"] integerValue] idNum:[dataDic objectForKey:@"id"] type:[[dataDic objectForKey:@"type"] integerValue] zoomImage:[dataDic objectForKey:@"cover_route_map_cover"]];
                    [_indexThreeArray addObject:destination];
                }
            }
            if (aIndex == 4) {
                for (NSDictionary *dataDic in dataArr) {
                    Destination *destination = [Destination destiationWithVistCount:[[dataDic objectForKey:@"visited_count"] integerValue] name:[dataDic objectForKey:@"name"] cover:[dataDic objectForKey:@"cover"] wishCount:[[dataDic objectForKey:@"wish_to_go_count"] integerValue] idNum:[dataDic objectForKey:@"id"] type:[[dataDic objectForKey:@"type"] integerValue] zoomImage:[dataDic objectForKey:@"cover_route_map_cover"]];
                    [_indexFourArray addObject:destination];
                }
            }
            if (aIndex == 3) {
                for (NSDictionary *dataDic in dataArr) {
                    Destination *destination = [Destination destiationWithVistCount:[[dataDic objectForKey:@"visited_count"] integerValue] name:[dataDic objectForKey:@"name"] cover:[dataDic objectForKey:@"cover"] wishCount:[[dataDic objectForKey:@"wish_to_go_count"] integerValue] idNum:[dataDic objectForKey:@"id"] type:[[dataDic objectForKey:@"type"] integerValue] zoomImage:[dataDic objectForKey:@"cover_route_map_cover"]];
                    [_indexFiveArray addObject:destination];
                }
            }
            if (aIndex == 5) {
                for (NSDictionary *dataDic in dataArr) {
                    Destination *destination = [Destination destiationWithVistCount:[[dataDic objectForKey:@"visited_count"] integerValue] name:[dataDic objectForKey:@"name"] cover:[dataDic objectForKey:@"cover"] wishCount:[[dataDic objectForKey:@"wish_to_go_count"] integerValue] idNum:[dataDic objectForKey:@"id"] type:[[dataDic objectForKey:@"type"] integerValue] zoomImage:[dataDic objectForKey:@"cover_route_map_cover"]];
                    [_indexSixArray addObject:destination];
                }
            }
            if (aIndex == 6) {
                for (NSDictionary *dataDic in dataArr) {
                    Destination *destination = [Destination destiationWithVistCount:[[dataDic objectForKey:@"visited_count"] integerValue] name:[dataDic objectForKey:@"name"] cover:[dataDic objectForKey:@"cover"] wishCount:[[dataDic objectForKey:@"wish_to_go_count"] integerValue] idNum:[dataDic objectForKey:@"id"] type:[[dataDic objectForKey:@"type"] integerValue] zoomImage:[dataDic objectForKey:@"cover_route_map_cover"]];
                    [_indexSevenArray addObject:destination];
                }
            }
            [_indexArray addObject:indexdes];
        }
        [_titleCollection reloadData];
    }];
}




- (void)receiveIndex:(NSIndexPath *)indexPath WithType:(NSInteger)type idNum:(id)idNum destination:(Destination *)destination{
    
    DesDetailController *deatil = [[DesDetailController alloc] init];
    deatil.type = type;
    deatil.idNum = idNum;
    deatil.destination = destination;
    deatil.navigationItem.title = destination.name;
    deatil.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0f green:160 / 255.0f blue:175 / 255.0f alpha:1];
    
    [self.navigationController pushViewController:deatil animated:YES];
    [deatil release];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImage *deSel = [UIImage imageNamed:@"didians"];
    deSel = [deSel imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarController.tabBar.selectedItem.selectedImage = deSel;
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0f green:160 / 255.0f blue:175 / 255.0f alpha:1];
    
    self.navigationItem.title = @"想去哪玩";
    [self createSegmentedControl];
    [self createCollectionView];
    [self getMessage];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
